<?php

namespace Home\Controller;

use Common\Top;
use Common\Utils;
use Think\Controller;

class ProductController extends CommonController
{


    public function index()
    {
        $userList = $this->userInfo;

        $page = I('page');

        if ($page == '') {
            $page = 1;
        }

        $html = $this->productListGetPageHtml($page);

        if (IS_POST && IS_AJAX) {
            $this->ajaxReturn($html);
        } else {
            $this->assign('html', $html);
        }

        $domain = $_SERVER['SERVER_NAME'];
        $domain = "http://" . $domain . "/index.php/Home/Product/index.html";
        $this->assign('domain', $domain);
        $this->assign('userList', $userList);
        $this->display();
    }



    public function lists()
    {
        $userList = $this->userInfo;

        $page = I('page');

        if ($page == '') {
            $page = 1;
        }
        $html = $this->productMoreGetPageHtml($page);

        if (IS_POST && IS_AJAX) {
            $this->ajaxReturn($html);
        } else {
            $this->assign('html', $html);
        }

        $id = I('id');
        $domain = $_SERVER['SERVER_NAME'];
        $domain = "http://" . $domain . "/index.php/Home/Around/lists/id/{$id}.html";
        $this->assign('domain', $domain);
        $this->assign('id', $id);
        $this->assign('userList', $userList);
        $this->display();
    }



    protected function productListGetPageHtml($page)
    {
        $M = M();
        $userList = $this->userInfo;

        $pageSize = C('PRODUCT_PAGE_SET');
        $index = ($page - 1) * $pageSize;

        $where['operator_id'] = $userList['operator_id'];
        $where['state'] = Top::ProductStateIsSale;

        $list = $M->table('top_product')
            ->where($where)
            ->field('id,name,price_agency,cover_pic,order_num')
            ->order('order_num desc,id desc')
            ->limit($index, $pageSize)
            ->select();

        $Pic = array();

        foreach ($list as $key => $vo) {
            $vo['price_agency'] = Utils::getYuan($vo['price_agency']);
            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 300, 300, 1);

            if ($vo['cover_pic'] == '') {
                $coverPic = "<img class='lazy' data-original='http://file1.lydlr.com/c/300/300/tour/2016/0722/01414731830.jpg'/>";
            } else {
                $coverPic = "<img class='lazy' data-original='" . $Pic[$key] . "'/>";
            }

            $evaldata .= "<dl class='item clearfix'>";
            $evaldata .= "<dt><a href=" . U('Product/lists', array('id' => $vo['id'])) . ">" . $coverPic . "</a></dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<a href=" . U('Product/lists', array('id' => $vo['id'])) . ">";
            $evaldata .= "<p class='name'>" . $vo['name'] . "</p>";
            $evaldata .= "<p class='bt' style='margin-left:-20px'><span class='price'><dfn>&yen;" . $vo['price_agency'] . "</dfn>起</span></p>";
            $evaldata .= "</a>";
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
        }

        return $evaldata;
    }


    protected function productMoreGetPageHtml($page)
    {
        $M = M();
        $where['id'] = I('id');

        $operatorId = $this->shareOperators;
        $where['operator_id'] = array('in', $operatorId);
        $where['state'] = Top::ProductStateIsSale;

        $pageSize = C('PRODUCT_PAGE_SET');
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_product')
            ->where($where)
            ->field('id,name,price_agency,cover_pic')
            ->order('id desc')
            ->limit($index, $pageSize)
            ->select();
        $Pic = array();

        foreach ($list as $key => $vo) {
            $vo['price_agency'] = Utils::getYuan($vo['price_agency']);
            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 300, 300, 1);

            if ($vo['cover_pic'] == '') {
                $coverPic = "<img src='http://file1.lydlr.com/c/300/300/tour/2016/0722/01414731830.jpg'/>";
            } else {
                $coverPic = "<img src='" . $Pic[$key] . "'/>";
            }

            $evaldata .= "<dl class='item clearfix'>";
            $evaldata .= "<dt><a href=" . U('Product/details', array('id' => $vo['id'])) . ">" . $coverPic . "</a></dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<a href=" . U('Product/details', array('id' => $vo['id'])) . ">";
            $evaldata .= "<p class='name'>" . $vo['name'] . "</p>";
            $evaldata .= "<div class='mid clearfix'>";
            $evaldata .= "<span class='tag pull-left'>通用产品</span>";
            $evaldata .= "<span class='price pull-right'><dfn>&yen;" . $vo['price_agency'] . "</dfn>起</span>";
            $evaldata .= "</div>";
            $evaldata .= "<div class='bottom clearfix'>";
            $evaldata .= "<span class='ck pull-right'>[详情]</span>";
            $evaldata .= "</div>";
            $evaldata .= "</a>";
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
        }

        return $evaldata;
    }



    public function details()
    {

        if ($this->userInfo) {
            $userList['agency'] = $this->userInfo;
        }

        $qq = intval($userList['agency']['qq']);
        $id = I('id', 0, 'int');

        $mobile = $userList['agency']['mobile'];

        $list = M('product')->where("id = '{$id}'")->find();

        $where['entity_id'] = $list['user_id'];
        $where['entity_type'] = Top::EntityTypeProvider;
        $contactPhone = M('user')->where($where)->field('mobile')->find();
        $contactPhone = $contactPhone['mobile'];

        $domain = $_SERVER['SERVER_NAME'];
        $domain = "http://" . $domain . "/index.php/Home/Product/details/id/{$id}.html";

        $this->assign('contactPhone', $contactPhone);
        $this->assign('list', $list);
        $this->assign('domain', $domain);
        $this->assign('qq', $qq);
        $this->assign('mobile', $mobile);
        $this->display();
    }



    public function orderInfo()
    {
        $M = M();
        $userList = $this->userInfo;
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            if (IS_POST && IS_AJAX) {
                if ($userList['account_state'] != 1) {
                    $data['status'] = 0;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                $postCode = I('code');
                $code = session('orderInfoCode');

                if ($postCode == $code) {
                    session('orderInfoCode', null);
                    $id = I('id');
                    $keyid = Utils::getDecrypt(I('keyid'));

                    if ($id != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }


                    $productInfo = M('product')->where("id = '{$id}'")->find();

                    $providerId = $productInfo['provider_id'];

                    if ($providerId != '0') {
                        $data['provider_operator_id'] = $productInfo['operator_id'];
                        $data['provider_id'] = $providerId;
                    } else {
                        $data['provider_operator_id'] = 0;
                        $data['provider_id'] = 0;
                    }

                    $providerInfo = M('provider')->where("id = '{$providerId}'")->field('id,name')->find();
                    $data['agency_id'] = $userList['id'];
                    $data['agency_operator_id'] = $userList['operator_id'];
                    $data['agency_name'] = $userList['name'];
                    $data['product_id'] = $id;
                    $data['provider_name'] = $providerInfo['name'];
                    $data['product_name'] = $productInfo['name'];
                    $data['contacts'] = I('contacts');
                    $data['contacts_phone'] = I('contact_phone');
                    $data['price_agency'] = $productInfo['price_agency'];
                    $data['price_cost'] = $productInfo['price_cost'];
                    $data['quantity'] = I('client_adult_count');
                    $data['para_type'] = $productInfo['para_type'];
                    $data['para_value'] = $productInfo['para_value'];
                    $data['order_sn'] = substr(date("YmdHis", time()) . rand(1000, 9999), 2);
                    $data['create_time'] = date('Y-m-d H:i:s', time());
                    $data['commission_rate'] = $productInfo['commission_rate'];
                    $data['memo'] = I('memo');
                    $data['state'] = Top::OrderStateSubmitted;

                    $adult_amount = (int)$data['quantity'] * $data['price_agency'];
                    //计算金额
                    $data['price_total'] = $adult_amount;
                    //将数据插入 order_tour 表
                    $result = $M->table('top_order_product')->add($data);

                    $orderInfo = M('order_product')->where("id = '{$result}'")->find();
                    $userInfo = M('user')->where("id = " . $productInfo['user_id'])->find();
                    $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                    array_shift($notifyMsgTypes);
                    array_pop($notifyMsgTypes);
                    $transactionMessage = $notifyMsgTypes[1];

                    $agencyNum = '(' . str_pad($userList['id'], 4, '0', STR_PAD_LEFT) . ')';
                    $content = '您的通用产品' . $orderInfo['product_name'] . '已被零售商' . $userList['name'] . '' . $agencyNum . '预定，请登录系统查看';
                    $template = array(
                        'touser' => $userInfo['weixinmp_openid'],
                        'template_id' => Utils::orderCreateSuccessTemplateId(),

                        'data' => array(
                            'first' => array('value' => urlencode($content), 'color' => "#000"),
                            'keyword1' => array('value' => urlencode($orderInfo['order_sn']), 'color' => "#000"),
                            'keyword2' => array('value' => urlencode(Utils::getYuan($orderInfo['price_total'])), 'color' => '#000'),
                            'keyword3' => array('value' => urlencode('已提交'), 'color' => '#000'),
                            'keyword4' => array('value' => urlencode($orderInfo['create_time']), 'color' => '#000'),
                            'keyword5' => array('value' => urlencode($orderInfo['product_name']), 'color' => '#000'),
                            'remark' => array('value' => urlencode(''), 'color' => '#000'),
                        )
                    );

                    if ($transactionMessage) {
                        $this->send_tpl($template);
                    }

                    if ($result && $result) {
                        $data['status'] = 1;
                        $data['msg'] = '提交成功';
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 2;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 3;
                    $data['msg'] = '请勿重复提交';
                    $this->ajaxReturn($data);
                }
            } else {
                $_SESSION['orderInfoCode'] = 400;
                $id = I('id', 0, 'int');

                $list = $M->table('top_product as t')
                    ->where("t.id = $id")
                    ->field(array(
                        't.id' => 'id',
                        't.name' => 'name',
                        't.price_agency' => 'price_agency',
                    ))
                    ->find();

                $list['price_agency'] = Utils::getYuan($list['price_agency']);

                $this->assign('userList', $userList);
                $this->assign('list', $list);
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
        $this->display();
    }


    /**
     * [showAllPayed付全款页面显示]
     */
    public function showAllPayed()
    {
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            $_SESSION['allPayedCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_order_product as o')
                ->where("o.id ='{$id}'")
                ->field(array(
                    'o.id' => 'id',
                    'o.product_name' => 'tour_name',
                    'o.quantity' => 'client_adult_count',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.state' => 'state',
                    'o.product_id' => 'product_id',
                    'o.memo' => 'memo',
                ))
                ->find();

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);

            $where['id'] = $orderTourList['product_id'];
            $productInfo = M('product')->where($where)->field('id,cover_pic')->find();
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $productInfo['cover_pic']);
            $coverPic = Utils::GetImageUrl($url, 240, 160, 1);

            $this->assign('productInfo', $productInfo);
            $this->assign('coverPic', $coverPic);
            $this->assign('userInfo', $userInfo);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }

    /**
     * [showPrePayed 付预付款页面显示]
     */
    public function showPrePayed()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $_SESSION['prePayedCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_order_product as o')
                ->where("o.id ='{$id}'")
                ->field(array(
                    'o.id' => 'id',
                    'o.product_name' => 'tour_name',
                    'o.quantity' => 'client_adult_count',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.product_id' => 'product_id',
                    'o.state' => 'state',
                    'o.prepay_amount' => 'prepay_amount',
                    'o.memo' => 'memo',
                ))
                ->find();

            $where['id'] = $orderTourList['product_id'];
            $productInfo = M('product')->where($where)->field('id,cover_pic')->find();

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $prepayAmount = Utils::getYuan($orderTourList['prepay_amount']);

            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $productInfo['cover_pic']);
            $coverPic = Utils::GetImageUrl($url, 240, 160, 1);

            $this->assign('userInfo', $userInfo);
            $this->assign('coverPic', $coverPic);
            $this->assign('productInfo', $productInfo);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);
            $this->assign('prepayAmount', $prepayAmount);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }

    /**
     * [showFinalPayment 付尾款页面显示]
     */
    public function showFinalPayment()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $_SESSION['preForumCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_order_product as o')
                ->where("o.id ='{$id}'")
                ->field(array(
                    'o.id' => 'id',
                    'o.product_name' => 'tour_name',
                    'o.quantity' => 'client_adult_count',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.state' => 'state',
                    'o.prepay_amount' => 'prepay_amount',
                    'o.memo' => 'memo',
                    'o.product_id' => 'product_id',
                ))
                ->find();

            $where['id'] = $orderTourList['product_id'];
            $productInfo = M('product')->where($where)->field('id,cover_pic')->find();
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $productInfo['cover_pic']);
            $coverPic = Utils::GetImageUrl($url, 240, 160, 1);

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $prepayAmount = Utils::getYuan($orderTourList['prepay_amount']);

            $preForum = $totalMoney - $prepayAmount;

            $this->assign('userInfo', $userInfo);
            $this->assign('coverPic', $coverPic);
            $this->assign('productInfo', $productInfo);
            $this->assign('preForum', $preForum);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);
            $this->assign('prepayAmount', $prepayAmount);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }

    /**
     * [allPayed 付全款]
     */
    public function allPayed()
    {
        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('allPayedCode');

            if ($postCode == $code) {
                session('allPayedCode', null);

                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStateAllPayed;
                $order_data['update_time'] = date('Y-m-d H:i:s', time());
                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '付款失败';
                    $this->ajaxReturn($data);
                }

                //查找线路id
                $list = M('order_product')->where($order_id)->find();
                $productInfo = M('product')->where("id = " . $list['product_id'])->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();
                $operatorId = $userList['operator_id'];
                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);
                //计算总价
                $totalMoneyFen = (int)$list['price_adjust'] + $list['price_total'];

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $totalMoneyFen) {
                    //开启事务
                    M('operator')->startTrans();
                    try {
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $totalMoneyFen) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }

                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $totalMoneyFen);

                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $totalMoneyFen);

                        $nowTime = Utils::getBatch();
                        //查找代理商id,显示单条数据
                        $agencyList = M('agency')->where("id = '{$entityId}'")->find();

                        $agency_data['operator_id'] = $operatorId;
                        $agency_data['action'] = '支出通用产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['amount'] = '-' . $totalMoneyFen;
                        $agency_data['balance'] = $agencyList['account_balance'];
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['remark'] = 'top_order_product.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeProduct;
                        $agency_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出通用产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $totalMoneyFen;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);


                        $providerId = $list['provider_id'];
                        $providerResult = M('provider')->where("id = '{$providerId}'")->setInc('account_balance', $totalMoneyFen);

                        $where['provider_id'] = $providerId;
                        $where['operator_id'] = $list['agency_operator_id'];
                        $agencyOperatorId = $list['agency_operator_id'];
                        $providerAccountInfo = M('provider_account')->where($where)->find();

                        if (!$providerAccountInfo) {
                            $providerAccountData['provider_name'] = $list['provider_name'];
                            $providerAccountData['provider_id'] = $providerId;
                            $providerAccountData['operator_id'] = $list['agency_operator_id'];
                            $providerAccountData['account'] = Utils::getNextAccount(3, $providerId);
                            $providerAccountData['account_balance'] = 0;
                            $providerAccountData['create_time'] = date("Y-m-d H:i:s", time());
                            M('provider_account')->add($providerAccountData);
                        }

                        $providerResult = M('provider_account')->where($where)->setInc('account_balance', $totalMoneyFen);
                        //查找运营商id，显示单条记录
                        $providerList = M('provider_account')->where($where)->find();
                        $operator_data['entity_id'] = $providerList['provider_id'];
                        $operator_data['operator_id'] = $providerList['operator_id'];
                        $operator_data['entity_type'] = Top::EntityTypeProvider;
                        $operator_data['action'] = '收入通用产品订单金额';
                        $operator_data['account'] = $providerList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['batch'] = $nowTime;
                        $operator_data['amount'] = $totalMoneyFen;
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['balance'] = $providerList['account_balance'];
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条运营商增钱的记录
                        $provider_addmoney = M('account_transaction')->add($operator_data);

                        $userInfo = M('user')->where("id = " . $productInfo['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];

                        $content = $agencyList['name'] . "已为" . $list['product_name'] . "订单付全款";
                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('全款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['product_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($totalMoneyFen)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $totalMoneyFen);
                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where("id = '{$providerId}'")->setDec('account_balance', $commissionFen);

                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where("id = '{$providerId}'")->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出通用产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['remark'] = 'top_order_product.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeProduct;
                            $provider_account_rate_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入通用产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeProduct;
                            $sys_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入通用产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeProduct;
                            $operator_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);
                        }

                        $state['payment_time'] = date("Y-m-d H:i:s", time());
                        $state['state'] = Top::OrderStateAllPayed;
                        $orderProductResult = M('order_product')->where($order_id)->save($state);

                        if ($result && $agency_delmoney && $providerResult && $provider_addmoney && $orderProductResult && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * [prePayed 付预付款]
     */
    public function prePayed()
    {

        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('prePayedCode');

            if ($postCode == $code) {
                session('prePayedCode', null);
                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStatePrepayed;
                $order_data['update_time'] = date('Y-m-d H:i:s', time());
                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '付款失败';
                    $this->ajaxReturn($data);
                }

                //查找线路id
                $list = M('order_product')->where($order_id)->find();
                $productInfo = M('product')->where("id = " . $list['product_id'])->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();
                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);

                //计算总价
                $prePayedMoney = intval($list['prepay_amount']);

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $prePayedMoney) {
                    //查找代理商id,显示单条数据
                    $agencyList = M('agency')->where("id = '{$entityId}'")->find();
                    $agencyAccountBalance = $agencyList['account_balance'];
                    //计算
                    $agencyAccountBalance = $agencyAccountBalance - $prePayedMoney;
                    M('operator')->startTrans();
                    try {
                        $operatorId = $userList['operator_id'];
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $prePayedMoney) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }

                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->execute("update top_agency set account_balance = '{$agencyAccountBalance}' where id = '{$entityId}'");
                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $prePayedMoney);

                        $nowTime = Utils::getBatch();
                        $agency_data['operator_id'] = $userList['operator_id'];
                        $agency_data['action'] = '支出通用产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['amount'] = -$prePayedMoney;
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['balance'] = $agencyAccountBalance;
                        $agency_data['remark'] = 'top_order_product.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeProduct;
                        $agency_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出通用产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $prePayedMoney;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);

                        $providerId = $list['provider_id'];
                        $providerResult = M('provider')->where("id = '{$providerId}'")->setInc('account_balance', $prePayedMoney);


                        $where['provider_id'] = $providerId;
                        $where['operator_id'] = $list['agency_operator_id'];
                        $agencyOperatorId = $list['agency_operator_id'];
                        $providerAccountInfo = M('provider_account')->where($where)->find();

                        if (!$providerAccountInfo) {
                            $providerAccountData['provider_name'] = $list['provider_name'];
                            $providerAccountData['provider_id'] = $providerId;
                            $providerAccountData['operator_id'] = $list['agency_operator_id'];
                            $providerAccountData['account'] = Utils::getNextAccount(3, $providerId);
                            $providerAccountData['account_balance'] = 0;
                            $providerAccountData['create_time'] = date("Y-m-d H:i:s", time());
                            M('provider_account')->add($providerAccountData);
                        }
                        $providerResult = M('provider_account')->where($where)->setInc('account_balance', $prePayedMoney);
                        //查找运营商id，显示单条记录
                        $providerList = M('provider_account')->where($where)->find();
                        $operator_data['entity_id'] = $providerList['provider_id'];
                        $operator_data['operator_id'] = $providerList['operator_id'];
                        $operator_data['entity_type'] = Top::EntityTypeProvider;

                        $operator_data['action'] = '收入通用产品订单金额';
                        $operator_data['amount'] = $prePayedMoney;
                        $operator_data['account'] = $providerList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['batch'] = $nowTime;
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['balance'] = $providerList['account_balance'];
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条供应商增钱的记录
                        $operator_addmoney = M('account_transaction')->add($operator_data);

                        $userInfo = M('user')->where("id = " . $productInfo['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];

                        $content = $agencyList['name'] . "已为" . $list['product_name'] . "订单付预付款";
                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('预付款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['product_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($prePayedMoney)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $prePayedMoney);
                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where("id = '{$providerId}'")->setDec('account_balance', $commissionFen);

                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where("id = '{$providerId}'")->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出通用产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['remark'] = 'top_order_product.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeProduct;
                            $provider_account_rate_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入通用产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeProduct;
                            $sys_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入通用产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeProduct;
                            $operator_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);
                        }

                        $state['payment_time'] = date("Y-m-d H:i:s", time());
                        $state['state'] = Top::OrderStatePrepayed;
                        $orderProductResult = M('order_product')->where($order_id)->save($state);

                        if ($result && $agency_delmoney && $providerResult && $operator_addmoney && $orderProductResult && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * [prePayed 付尾款]
     */
    public function preForum()
    {
        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('preForumCode');

            if ($postCode == $code) {
                session('preForumCode', null);

                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStateAllPayed;
                $order_data['update_time'] = date('Y-m-d H:i:s', time());
                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '付款失败';
                    $this->ajaxReturn($data);
                }
                //查找线路id
                $list = M('order_product')->where($order_id)->find();
                $productInfo = M('product')->where("id = " . $list['product_id'])->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();
                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);

                //计算总价
                $prePayedMoney = $list['price_total'] + $list['price_adjust'] - $list['prepay_amount'];

                if ($prePayedMoney == 0) {
                    $orderProductResult = M('order_product')->where($order_id)->save($order_data);

                    if ($orderProductResult) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }
                }

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $prePayedMoney) {
                    //查找代理商id,显示单条数据
                    $agencyList = M('agency')->where("id = '{$entityId}'")->find();
                    $agencyAccountBalance = intval($agencyList['account_balance']);
                    //计算
                    $agencyAccountBalance = $agencyAccountBalance - $prePayedMoney;
                    M('operator')->startTrans();
                    try {
                        $operatorId = $userList['operator_id'];
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $prePayedMoney) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }

                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $prePayedMoney);
                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $prePayedMoney);

                        $nowTime = Utils::getBatch();
                        $agency_data['operator_id'] = $userList['operator_id'];
                        $agency_data['action'] = '支出通用产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['amount'] = -$prePayedMoney;
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['balance'] = $agencyAccountBalance;
                        $agency_data['remark'] = 'top_order_product.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeProduct;
                        $agency_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出通用产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $prePayedMoney;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);


                        $providerId = $list['provider_id'];
                        $providerResult = M('provider')->where("id = '{$providerId}'")->setInc('account_balance', $prePayedMoney);

                        $where['provider_id'] = $providerId;
                        $where['operator_id'] = $list['agency_operator_id'];
                        $agencyOperatorId = $list['agency_operator_id'];
                        $providerResult = M('provider_account')->where($where)->setInc('account_balance', $prePayedMoney);
                        //查找运营商id，显示单条记录
                        $providerList = M('provider_account')->where($where)->find();
                        $operator_data['entity_id'] = $providerList['provider_id'];
                        $operator_data['operator_id'] = $providerList['operator_id'];
                        $operator_data['entity_type'] = Top::EntityTypeProvider;

                        $operator_data['action'] = '收入通用产品订单金额';
                        $operator_data['amount'] = $prePayedMoney;
                        $operator_data['account'] = $providerList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['batch'] = $nowTime;
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['balance'] = $providerList['account_balance'];
                        $operator_data['remark'] = 'top_order_product.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeProduct;
                        $operator_data['object_name'] = '通用产品';
                        //向 account_transaction 表插入一条供应商增钱的记录
                        $operator_addmoney = M('account_transaction')->add($operator_data);

                        $userInfo = M('user')->where("id = " . $productInfo['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];

                        $content = $agencyList['name'] . "已为" . $list['product_name'] . "订单付尾款";
                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('尾款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['product_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($prePayedMoney)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $prePayedMoney);
                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where("id = '{$providerId}'")->setDec('account_balance', $commissionFen);

                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where("id = '{$providerId}'")->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出通用产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['remark'] = 'top_order_product.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeProduct;
                            $provider_account_rate_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入通用产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeProduct;
                            $sys_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入通用产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_product.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeProduct;
                            $operator_account_data['object_name'] = '通用产品';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);
                        }

                        $state['payment_time'] = date("Y-m-d H:i:s", time());
                        $state['state'] = Top::OrderStateAllPayed;
                        $orderProductResult = M('order_product')->where($order_id)->save($state);

                        if ($result && $agency_delmoney && $providerResult && $operator_addmoney && $orderProductResult && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }

}
